/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.apache.coyote.http11;

import java.io.EOFException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Set;

import org.apache.coyote.ActionCode;
import org.apache.coyote.http11.filters.BufferedInputFilter;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.http.parser.HttpParser;
import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
import org.apache.tomcat.util.net.JIoEndpoint;
import org.apache.tomcat.util.net.SSLSupport;
import org.apache.tomcat.util.net.SocketStatus;
import org.apache.tomcat.util.net.SocketWrapper;


/**
 * Processes HTTP requests.
 *
 * @author Remy Maucherat
 * @author fhanik
 */
public class Http11Processor extends AbstractHttp11Processor<Socket> {

    private static final Log log = LogFactory.getLog(Http11Processor.class);
    @Override
    protected Log getLog() {
        return log;
    }

   // ------------------------------------------------------------ Constructor


    public Http11Processor(int headerBufferSize, boolean rejectIllegalHeader,
            JIoEndpoint endpoint, int maxTrailerSize, Set<String> allowedTrailerHeaders,
            int maxExtensionSize, int maxSwallowSize, String relaxedPathChars,
            String relaxedQueryChars) {

        super(endpoint);

        //创建http解析器
        httpParser = new HttpParser(relaxedPathChars, relaxedQueryChars);
        //创建数据接受的缓存区对象，缓冲区的buf设置为8*1024，是通过headerBufferSize传入的
        inputBuffer = new InternalInputBuffer(request, headerBufferSize, rejectIllegalHeader,
                httpParser);
        request.setInputBuffer(inputBuffer);

        //创建回写缓冲区的大小，缓冲区的大小和inputBuffer一样，其实inputBuffer和outputBuffer
        //就对应到了socket的inputstream和outputstream，这样来理解就好一点
        outputBuffer = new InternalOutputBuffer(response, headerBufferSize);
        //设置outputBuffer到response中
        response.setOutputBuffer(outputBuffer);

        initializeFilters(maxTrailerSize, allowedTrailerHeaders, maxExtensionSize, maxSwallowSize);
    }


    // ----------------------------------------------------- Instance Variables


    /**
     * Input.
     */
    protected InternalInputBuffer inputBuffer = null;


    /**
     * Output.
     */
    protected InternalOutputBuffer outputBuffer = null;


    /**
     * SSL information.
     */
    protected SSLSupport sslSupport;


    /**
     * The percentage of threads that have to be in use before keep-alive is
     * disabled to aid scalability.
     */
    private int disableKeepAlivePercentage = 75;

    // --------------------------------------------------------- Public Methods


    /**
     * Set the SSL information for this HTTP connection.
     */
    @Override
    public void setSslSupport(SSLSupport sslSupport) {
        this.sslSupport = sslSupport;
    }


    public int getDisableKeepAlivePercentage() {
        return disableKeepAlivePercentage;
    }


    public void setDisableKeepAlivePercentage(int disableKeepAlivePercentage) {
        this.disableKeepAlivePercentage = disableKeepAlivePercentage;
    }


    @Override
    protected boolean disableKeepAlive() {
        int threadRatio = -1;
        // These may return zero or negative values
        // Only calculate a thread ratio when both are >0 to ensure we get a
        // sensible result
        //maxThreads为线程池的最大线程数，threadsBusy表示正在忙的线程数（已分配执行的线程数）
        int maxThreads, threadsBusy;
        if ((maxThreads = endpoint.getMaxThreadsWithExecutor()) > 0
                && (threadsBusy = endpoint.getCurrentThreadsBusy()) > 0) {
            //如果正在忙的线程数除以最大的线程数 * 100得到一个数字
            threadRatio = (threadsBusy * 100) / maxThreads;
        }
        // Disable keep-alive if we are running low on threads
        //如果这个数字大于了75，证明现在剩余的线程数不多了，就需要关闭长连接
        if (threadRatio > getDisableKeepAlivePercentage()) {
            return true;
        }

        return false;
    }

    /**
     * 这个方法有两层意思，也就是做了两步操作：
     * 1.比如tomcat接受了一个请求，那么这个请求是要丢到线程池中运行的，丢到线程池中运行的时候需要
     * 对这个socket进行包装，也就是说丢到线程池中进行包装运行的时候记录一个时间，然后运行到这里的时候又有一个
     * 时间，那么要用运行到这里的时间减去丢到线程池的时间，也就是真正运行的是在这里，它要减去之前所做的一些操作
     * 而浪费的时间，简单来说就是超时时间需要重新计算，比如设置的超时时间是30s，然后从开启线程运行到这里所花费了2s
     * 那么真正的超时时间就是30-2=28s，然后计算出来过后从新设置超时时间。
     *
     * 2.第二步操作就是比较简单了，就是tomcat接受请求过后就需要读取数据，所以就是我们需要将请求流中的数据
     * 读取出来然后放入到tomcat这里的InputBuffer对象中的buf字节数组缓冲区里面，为后续的
     * 解析数据做准备，简单来说就是请求的时候将客户端的数据从inputstream中获取放入到tomcat自己的缓冲区
     * inputBuffer中，然后tomcat就从自己的缓冲区对象中去读取数据；而且这个从inputstream中读取数据
     * 的方法fill是可以多次调用的，比如inputstream中发送了1024k数据过来，而tomcat中的缓冲区只设置了
     * 512k的大小，那么一次只能读取到512k的数据，等tomcat将自己的缓冲区数据读取完成过后，发现还有数据，那么
     * 还会调用fill方法将剩余的数据读取过来
     * @throws IOException
     */
    @Override
    protected void setRequestLineReadTimeout() throws IOException {

        /*
         * When there is no data in the buffer and this is not the first
         * request on this connection and timeouts are being used the
         * first read for this request may need a different timeout to
         * take account of time spent waiting for a processing thread.
         *
         * This is a little hacky but better than exposing the socket
         * and the timeout info to the InputBuffer
         * inputBuffer中有两个很中重要的属性，pos和lastValid，pos就表示数据读取的开始位置
         * 而lastValid就表示数据读取了的位置，第一次读取的时候pos和lastvalid是一样的
         * 所以这里的这个if就是表示开始第一次读取，这个方法也是第一次读取才会调用，并且
         * 记录的执行的时间不能是-1，在请求过来的时候会将这个请求丢到线程池运行， 丢到线程池运行的时候
         * 是记录了时间的，也就是lastAccess
         */

        if (inputBuffer.lastValid == 0 && socketWrapper.getLastAccess() > -1) {
            int firstReadTimeout;
            //这个是从JioEnpoint中的保持一致的，就是连接超时时间，如果是-1，则设置
            //firstreadtimout为0，就表示马上超时了，不用读取数据了
            if (keepAliveTimeout == -1) {
                firstReadTimeout = 0;
            } else {
                //这里计算最终的超时时间，当前时间减去从线程运行到现在的时间，如果这个时间大于了
                //设置的超时时间，证明线程开始运行到现在就耗费完了所有的时间，就直接超时了
                //这里的直接超时是将firstReadTimeout设置为1毫秒
                long queueTime =
                    System.currentTimeMillis() - socketWrapper.getLastAccess();

                if (queueTime >= keepAliveTimeout) {
                    // Queued for longer than timeout but there might be
                    // data so use shortest possible timeout
                    firstReadTimeout = 1;
                } else {
                    // Cast is safe since queueTime must be less than
                    // keepAliveTimeout which is an int
                    //得到最终的超时时间
                    firstReadTimeout = keepAliveTimeout - (int) queueTime;
                }
            }
            //重新设置超时时间
            socketWrapper.getSocket().setSoTimeout(firstReadTimeout);
            //数据的读取，这里的数据读取就是在方法前面写的注释的第二步操作,就是讲socket中
            //inputStream流中的数据（请求过来的数据）读取到inputBuffer中的buf中，这个buf的大小是
            //默认是8 * 1024 就是8kb
            if (!inputBuffer.fill()) {
                throw new EOFException(sm.getString("iib.eof.error"));
            }
            // Once the first byte has been read, the standard timeout should be
            // used so restore it here.
            //上面设置的超时时间是当前socket的，这里设置的超时时间是全局的
            if (endpoint.getSoTimeout()> 0) {
                setSocketTimeout(endpoint.getSoTimeout());
            } else {
                setSocketTimeout(0);
            }
        }
    }


    @Override
    protected boolean handleIncompleteRequestLineRead() {
        // Not used with BIO since it uses blocking reads
        return false;
    }


    @Override
    protected void setSocketTimeout(int timeout) throws IOException {
        socketWrapper.getSocket().setSoTimeout(timeout);
    }


    @Override
    protected void setCometTimeouts(SocketWrapper<Socket> socketWrapper) {
        // NO-OP for BIO
    }


    @Override
    protected boolean breakKeepAliveLoop(SocketWrapper<Socket> socketWrapper) {
        openSocket = keepAlive;
        // If we don't have a pipe-lined request allow this thread to be
        // used by another connection
        if (inputBuffer.lastValid == 0) {
            return true;
        }
        return false;
    }


    @Override
    protected void resetTimeouts() {
        // NOOP for BIO
    }


    @Override
    protected void recycleInternal() {
        // Recycle
        this.socketWrapper = null;
        // Recycle ssl info
        sslSupport = null;
    }


    @Override
    public SocketState event(SocketStatus status) throws IOException {
        // Should never reach this code but in case we do...
        throw new IOException(
                sm.getString("http11processor.comet.notsupported"));
    }

    // ----------------------------------------------------- ActionHook Methods


    /**
     * Send an action to the connector.
     *
     * @param actionCode Type of the action
     * @param param Action parameter
     */
    @SuppressWarnings("incomplete-switch") // Other cases are handled by action()
    @Override
    public void actionInternal(ActionCode actionCode, Object param) {

        switch (actionCode) {
        case REQ_SSL_ATTRIBUTE: {
            try {
                if (sslSupport != null) {
                    Object sslO = sslSupport.getCipherSuite();
                    if (sslO != null)
                        request.setAttribute
                            (SSLSupport.CIPHER_SUITE_KEY, sslO);
                    sslO = sslSupport.getPeerCertificateChain(false);
                    if (sslO != null)
                        request.setAttribute
                            (SSLSupport.CERTIFICATE_KEY, sslO);
                    sslO = sslSupport.getKeySize();
                    if (sslO != null)
                        request.setAttribute
                            (SSLSupport.KEY_SIZE_KEY, sslO);
                    sslO = sslSupport.getSessionId();
                    if (sslO != null)
                        request.setAttribute
                            (SSLSupport.SESSION_ID_KEY, sslO);
                    sslO = sslSupport.getProtocol();
                    if (sslO != null) {
                        request.setAttribute
                            (SSLSupport.PROTOCOL_VERSION_KEY, sslO);
                    }
                    request.setAttribute(SSLSupport.SESSION_MGR, sslSupport);
                }
            } catch (Exception e) {
                log.warn(sm.getString("http11processor.socket.ssl"), e);
            }
            break;
        }
        case REQ_HOST_ADDR_ATTRIBUTE: {
            if ((remoteAddr == null) && (socketWrapper != null)) {
                InetAddress inetAddr = socketWrapper.getSocket().getInetAddress();
                if (inetAddr != null) {
                    remoteAddr = inetAddr.getHostAddress();
                }
            }
            request.remoteAddr().setString(remoteAddr);
            break;
        }
        case REQ_LOCAL_NAME_ATTRIBUTE: {
            if ((localName == null) && (socketWrapper != null)) {
                InetAddress inetAddr = socketWrapper.getSocket().getLocalAddress();
                if (inetAddr != null) {
                    localName = inetAddr.getHostName();
                }
            }
            request.localName().setString(localName);
            break;
        }
        case REQ_HOST_ATTRIBUTE: {
            if ((remoteHost == null) && (socketWrapper != null)) {
                InetAddress inetAddr = socketWrapper.getSocket().getInetAddress();
                if (inetAddr != null) {
                    remoteHost = inetAddr.getHostName();
                }
                if(remoteHost == null) {
                    if(remoteAddr != null) {
                        remoteHost = remoteAddr;
                    } else { // all we can do is punt
                        request.remoteHost().recycle();
                    }
                }
            }
            request.remoteHost().setString(remoteHost);
            break;
        }
        case REQ_LOCAL_ADDR_ATTRIBUTE: {
            if (localAddr == null)
               localAddr = socketWrapper.getSocket().getLocalAddress().getHostAddress();

            request.localAddr().setString(localAddr);
            break;
        }
        case REQ_REMOTEPORT_ATTRIBUTE: {
            if ((remotePort == -1 ) && (socketWrapper !=null)) {
                remotePort = socketWrapper.getSocket().getPort();
            }
            request.setRemotePort(remotePort);
            break;
        }
        case REQ_LOCALPORT_ATTRIBUTE: {
            if ((localPort == -1 ) && (socketWrapper !=null)) {
                localPort = socketWrapper.getSocket().getLocalPort();
            }
            request.setLocalPort(localPort);
            break;
        }
        case REQ_SSL_CERTIFICATE: {
            if (sslSupport != null) {
                /*
                 * Consume and buffer the request body, so that it does not
                 * interfere with the client's handshake messages
                 */
                InputFilter[] inputFilters = inputBuffer.getFilters();
                ((BufferedInputFilter) inputFilters[Constants.BUFFERED_FILTER])
                    .setLimit(maxSavePostSize);
                inputBuffer.addActiveFilter
                    (inputFilters[Constants.BUFFERED_FILTER]);
                try {
                    Object sslO = sslSupport.getPeerCertificateChain(true);
                    if( sslO != null) {
                        request.setAttribute
                            (SSLSupport.CERTIFICATE_KEY, sslO);
                    }
                } catch (Exception e) {
                    log.warn(sm.getString("http11processor.socket.ssl"), e);
                }
            }
            break;
        }
        case ASYNC_COMPLETE: {
            if (asyncStateMachine.asyncComplete()) {
                ((JIoEndpoint) endpoint).processSocketAsync(this.socketWrapper,
                        SocketStatus.OPEN_READ);
            }
            break;
        }
        case ASYNC_SETTIMEOUT: {
            if (param == null) return;
            long timeout = ((Long)param).longValue();
            // if we are not piggy backing on a worker thread, set the timeout
            socketWrapper.setTimeout(timeout);
            break;
        }
        case ASYNC_DISPATCH: {
            if (asyncStateMachine.asyncDispatch()) {
                ((JIoEndpoint) endpoint).processSocketAsync(this.socketWrapper,
                        SocketStatus.OPEN_READ);
            }
            break;
        }
        }
    }


    // ------------------------------------------------------ Protected Methods


    @Override
    protected void prepareRequestInternal() {
        // NOOP for BIO
    }

    @Override
    protected boolean prepareSendfile(OutputFilter[] outputFilters) {
        // Should never, ever call this code
        Exception e = new Exception();
        log.error(sm.getString("http11processor.neverused"), e);
        return false;
    }

    @Override
    protected AbstractInputBuffer<Socket> getInputBuffer() {
        return inputBuffer;
    }

    @Override
    protected AbstractOutputBuffer<Socket> getOutputBuffer() {
        return outputBuffer;
    }

    /**
     * Set the socket buffer flag.
     */
    @Override
    public void setSocketBuffer(int socketBuffer) {
        super.setSocketBuffer(socketBuffer);
        outputBuffer.setSocketBuffer(socketBuffer);
    }
}
